import { auth, conf, fop, util } from 'qiniu';
import './interfaces';

const AK = 'EuAlexLFzRBCAO0vyxEeJSyAtwISmg9y6MW-6CuY';
const EXPIRES = 72000;
const SK = 'JDX6tv_BpYvFuP9lvRz0pY_1PPn5dxemSNaS-UZv';
const bucket = 'test';

const mac = new auth.digest.Mac(AK, SK);
const config = new conf.Config();
const operManager = new fop.OperationManager(mac, config);

export default async function atom(msg: {
	file_name: string;
	height: number;
	width: number;
}) {
	const file_name = msg.file_name;
	const preview = file_name + 'preview.mp4';
	const cover = file_name + 'preview.jpg';
	const p = util.urlsafeBase64Encode(`${bucket}:${preview}`);
	const c = util.urlsafeBase64Encode(`${bucket}:${cover}`);
	const max = 320;
	const m = Math.max(msg.width, msg.height);
	const rate = max / m;
	const w = (msg.width * rate).toFixed(0);
	const h = (msg.height * rate).toFixed(0);
	const fops = [
		`avthumb/mp4/vcodec/libx264|saveas/${p}`,
		`vframe/jpg/offset/1/w/${w}/h/${h}|saveas/${c}`
	];
	const srcKey = file_name;
	const saveBucket = bucket;

	const pipeline = bucket;
	const srcBucket = bucket;
	const options = {};
	return new Promise<{
		persistent_id: string;
		preview: string;
		cover: string;
	}>((resolve, reject) => {
		// 持久化数据处理返回的是任务的 persistentId，可以根据这个id查询处理状态
		operManager.pfop(srcBucket, srcKey, fops, pipeline, options, (err, respBody, respInfo) => {
			if (err) {
				reject(err);
				return;
			}
			resolve({
				cover,
				persistent_id: respBody.persistentId,
				preview
			});
		});
	});
}